var express = require('express');
var router = express.Router();


/**https://github.com/FrontendMagazine/Works/blob/master/archive/token-based_authentication_with_angularjs_%26_nodejs.md
 * jwt 验证
 * https://segmentfault.com/a/1190000009494020
 */

var jwt = require('jsonwebtoken');
var passport = require('passport');
var passportJWT = require('passport-jwt');

var ExtractJwt = passportJWT.ExtractJwt;
var JwtStrategy = passportJWT.Strategy;//策略

var jwtOptions = {};
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
jwtOptions.secretOrKey = 'szjedu';

router.use('/login', function (req, res, next) {

  req.user = { id: 1, name: "admin", password: "admin" };
  var strategy = new JwtStrategy(jwtOptions, function (jwt_payload, next) {

    // usually this would be a database call:

    var user = jwt_payload;
    // console.log(jwt_payload.id);
    if (user) {
      next(null, user);
    } else {
      next(null, false);
    }
  });
  passport.use(strategy) //使用策略
  next();
})
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { message: "Hello world" });
});

router.post("/login", function (req, res) {

  if (req.body.name && req.body.password) {
    var name = req.body.name;
    var password = req.body.password;
  }
  // usually this would be a database call:
  var user = req.user;
  if (!user) {
    res.status(401).json({ message: "找不到用户" });
    res.end();
  }

  if (user.password === req.body.password) {
    // from now on we'll identify the user by the id and the id is the only personalized value that goes into our token
    var payload = { id: user.id };

    var token = jwt.sign(user, jwtOptions.secretOrKey, { subject: "baidu.com" });//设置时间expiresIn: 3600,audience:"baidu.com",subject:"baidu.com"
    res.cookie('token', token, { httpOnly: true });
    res.json({ message: "ok", user: user, token: token });

    res.end();
  } else {
    res.status(401).json({ message: "密码不匹配" });
    res.end();
  }
});

router.get("/secret", passport.authenticate('jwt', { session: false }), function (req, res) {

  //可以使用token 和 存储的token进行比较 如果相同 继续 不同 返回登陆


  res.json({ message: "Success!" });
});
router.get('/sss', function (req, res) {
  var request = require("request");
  console.log(req.cookies['token']);
  var options = {
    method: 'GET',
    url: 'http://localhost:3000/secret',
    headers:
    {
      authorization: 'JWT ' + req.cookies['token']
    }
  };
  var aa = jwt.verify(req.cookies['token'], jwtOptions.secretOrKey);
  console.log(aa); //验证有效性
  var bb = jwt.decode(req.cookies['token']); //不验证有效性
  console.log(bb);
  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    res.json(body);
  });
})

module.exports = router;
